import config from '@/config.js'
import platform from './platform.js'
import performance from './performance.js'

// API请求基础配置
const BASE_URL = config.baseUrl
const TIMEOUT = 10000

// 请求拦截器
const requestInterceptor = (config) => {
  // 添加token
  const token = platform.getStorage('token')
  if (token) {
    config.header = config.header || {}
    config.header.Authorization = `Bearer ${token}`
  }

  // 添加平台标识
  config.header = config.header || {}
  config.header['X-Platform'] = platform.getPlatform()
  
  return config
}

// 请求方法
const request = (options = {}) => {
  return new Promise((resolve, reject) => {
    // 获取token
    const token = uni.getStorageSync('token')
    
    // 获取平台特定配置
    const platformConfig = platform.getRequestConfig()
    
    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        ...platformConfig.header,
        'Authorization': token ? `Bearer ${token}` : '',
        ...options.header
      },
      timeout: options.timeout || platformConfig.timeout,
      success: (res) => {
        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            resolve(res.data)
          } else if (res.data.code === 401) {
            // token过期，跳转登录
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            
            // #ifdef MP-WEIXIN
            uni.showModal({
              title: '提示',
              content: '登录已过期，请重新登录',
              showCancel: false,
              success: () => {
                uni.reLaunch({
                  url: '/pages/login'
                })
              }
            })
            // #endif
            
            // #ifdef H5
            uni.showToast({
              title: '登录已过期，请重新登录',
              icon: 'none'
            })
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/login'
              })
            }, 1500)
            // #endif
            
            // #ifdef APP-PLUS
            uni.showModal({
              title: '提示',
              content: '登录已过期，请重新登录',
              showCancel: false,
              success: () => {
                uni.reLaunch({
                  url: '/pages/login'
                })
              }
            })
            // #endif
            
            reject(res.data)
          } else {
            // 业务错误
            uni.showToast({
              title: res.data.msg || '请求失败',
              icon: 'none'
            })
            reject(res.data)
          }
        } else {
          // HTTP错误
          let errorMsg = '请求失败'
          
          // #ifdef MP-WEIXIN
          if (res.statusCode === 404) {
            errorMsg = '接口不存在'
          } else if (res.statusCode === 500) {
            errorMsg = '服务器错误'
          } else if (res.statusCode === 403) {
            errorMsg = '权限不足'
          }
          // #endif
          
          // #ifdef H5
          if (res.statusCode === 404) {
            errorMsg = '接口不存在'
          } else if (res.statusCode === 500) {
            errorMsg = '服务器内部错误'
          } else if (res.statusCode === 403) {
            errorMsg = '访问被拒绝'
          } else if (res.statusCode === 0) {
            errorMsg = '网络连接失败'
          }
          // #endif
          
          uni.showToast({
            title: errorMsg,
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: (err) => {
        console.error('请求失败:', err)
        
        let errorMsg = '网络请求失败'
        
        // #ifdef MP-WEIXIN
        if (err.errMsg && err.errMsg.includes('timeout')) {
          errorMsg = '请求超时，请检查网络'
        } else if (err.errMsg && err.errMsg.includes('fail')) {
          errorMsg = '网络连接失败'
        }
        // #endif
        
        // #ifdef H5
        if (err.message && err.message.includes('timeout')) {
          errorMsg = '请求超时'
        } else if (err.message && err.message.includes('Network Error')) {
          errorMsg = '网络连接错误'
        }
        // #endif
        
        // #ifdef APP-PLUS
        if (err.errMsg && err.errMsg.includes('timeout')) {
          errorMsg = '请求超时'
        } else if (err.errMsg && err.errMsg.includes('fail')) {
          errorMsg = '网络不可用'
        }
        // #endif
        
        uni.showToast({
          title: errorMsg,
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

// 封装常用请求方法
export default {
  // GET请求
  get(url, params = {}) {
    const queryString = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')

    const fullUrl = queryString ? `${url}?${queryString}` : url

    return performance.request.add(() => request({
      url: fullUrl,
      method: 'GET'
    }))
  },

  // POST请求
  post(url, data = {}) {
    return performance.request.add(() => request({
      url,
      method: 'POST',
      data
    }))
  },

  // PUT请求
  put(url, data = {}) {
    return performance.request.add(() => request({
      url,
      method: 'PUT',
      data
    }))
  },

  // DELETE请求
  delete(url) {
    return performance.request.add(() => request({
      url,
      method: 'DELETE'
    }))
  },

  // 文件上传
  upload(url, filePath, formData = {}) {
    return new Promise((resolve, reject) => {
      const token = platform.getStorage('token')

      uni.uploadFile({
        url: BASE_URL + url,
        filePath,
        name: 'file',
        formData,
        header: {
          Authorization: token ? `Bearer ${token}` : '',
          'X-Platform': platform.getPlatform()
        },
        success: (response) => {
          try {
            const data = JSON.parse(response.data)
            if (data.code === 200) {
              resolve(data.data)
            } else {
              platform.showToast(data.message || '上传失败', 'none')
              reject(new Error(data.message || '上传失败'))
            }
          } catch (error) {
            reject(error)
          }
        },
        fail: (error) => {
          console.error('上传失败:', error)
          platform.showToast('上传失败', 'none')
          reject(error)
        }
      })
    })
  },

  // 下载文件
  download(url, savePath) {
    return new Promise((resolve, reject) => {
      uni.downloadFile({
        url: BASE_URL + url,
        success: (response) => {
          if (response.statusCode === 200) {
            resolve(response.tempFilePath)
          } else {
            reject(new Error('下载失败'))
          }
        },
        fail: reject
      })
    })
  }
}